import {WeaDialog, WeaTableEdit} from 'ecCom';
import {Button, DatePicker, TimePicker, Form, Modal} from 'antd';
import moment from 'moment';
import * as Apis from '../../../../apis/previewMeeting';
const FormItem = Form.Item;
import {inject, observer} from 'mobx-react';
import {WeaLocaleProvider, WeaRangePicker} from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

@inject('meetingDialog')
@observer
class MeetTopicTimeForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {datas: []};
  }

  componentDidMount() {
    this.props.initFunc && this.props.initFunc(this);
  }

  render() {
    let {form} = this.props;
    let {datas = []} = this.state;
    return (
      <Form ecId={`${this && this.props && this.props.ecId || ''}_Form@rw3e3j`} inline>
        <WeaTableEdit ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEdit@41v1dy`}
          columns={this.getTimeTableColumns(form)}
          datas={datas}
          title={getLabel(383563, "时间安排")}
          tableProps={{scroll: {y: 315}}}
          ref="tableEdit"
          onChange={this.onChange}
        />
      </Form>
    );
  }

  getTimeTableColumns = (form) => {
    const {getFieldProps} = form;
    return [{
      title: <span style={{marginRight: "70px"}}>{getLabel(124799, "日期范围")}</span>,
      dataIndex: "range",
      key: "range",
      viewAttr: 3,
      width: '100%',
      com: [
        {
          type: 'custom',
          key: 'range',
          render: (text, record, index) => {
            let data = record || {};
            let begin = data.begindate ? data.begindate + " " + (data.begintime || "00:00") : undefined;
            let end = data.enddate ? data.enddate + " " + (data.endtime || "00:00") : undefined;
            if(record.range){
              begin=record.range[0];
              end=record.range[1];
            }
            let props = getFieldProps("_" + index, {
              // rules: [
              //   { required: true, message: "请选择日期范围"},
              //   {
              //     validator: (rule, value, callback) => {
              //       if (!Array.isArray(value) || value.some((s) => !s)) {
              //         callback(getLabel(383565, "请选择日期范围"));
              //       } else
              //         callback();
              //
              //     }
              //   }
              // ],
              initialValue: [
                begin,
                end
              ]
            });
            return (
              <FormItem ecId={`${this && this.props && this.props.ecId || ''}_FormItem@5fksh7@schedule`}>
                <WeaRangePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaRangePicker@mwdr53@schedule`}
                  {...props}
                  viewAttr = {3}
                  format="yyyy-MM-dd HH:mm"
                  showTime={true}
                  onChange={v => {this.datePickerChange(index, v)}}
                />
              </FormItem>
            );
          }
        }
      ]
    }];
  }

  datePickerChange = (index, v) => {
    if(v[0] == '' || v[1] == ''){
      let data = {...this.state.datas[index]};
      let datas = [...this.state.datas];
      data.begindate ='';
      data.begintime= '';
      data.enddate = '';
      data.endtime= '';
      datas[index] = data;
      this.onChange(datas);
    }else{
      let data = {...this.state.datas[index]};
      let datas = [...this.state.datas];
      let beginMoment = moment(v[0]);
      let endMoment = moment(v[1]);
  
      data.begindate = beginMoment.format("YYYY-MM-DD");
      data.begintime= beginMoment.format("HH:mm");
      data.enddate = endMoment.format("YYYY-MM-DD");
      data.endtime= endMoment.format("HH:mm");
  
      datas[index] = data;
      this.onChange(datas);
    }
  }

  validateFieldsAndScroll = (callback) => {
    // this.props.form.validateFieldsAndScroll((errors, values) => {
    //   if (!!errors) {
    //     return;
    //   }
    //   callback(values);
    // });
    const datas = [...this.state.datas];
    let canSubmit  = true;
    datas.map(v => {
      if(!v.range || v.range == ''){
        canSubmit = false;
      }

      //2种格式数据处理
      if(!canSubmit && v.begindate && v.begindate!=''){
        canSubmit=true;
      }
    })
    if(canSubmit){
      if(callback)callback(datas);
    }else {
      Modal.error({
        title: getLabel(15172,'系统提示'),
        content: getLabel(383565, "请选择日期范围")
      });
    }
  }


  onChange = (datas)=>{
    this.setState({
      datas: datas
    });
   // this.form.
  }

  clear = ()=>{
    this.setState({
      datas: []
    });
  }
};
MeetTopicTimeForm = Form.create()(MeetTopicTimeForm);


@inject('meetingDialog')
@observer
class MeetTopicTimeDialog extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      record: {},
    };
  }

  render() {
    let {visible, record} = this.state;
    let {titleKey} = this.props;
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@obicse`} visible={visible}
                 title={`${getLabel(383566, "设置会议议程")}：${record[titleKey] || ''}`}
                 className='wea-meeting-decisionSet'
                 style={{width: 600, height: 400}}
                 icon="icon-coms-meeting"
                 iconBgcolor="#f14a2d"
                 onCancel={this.back}
                 buttons={[
                   <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@b8mli9@submit`} type="primary" onClick={this.submit}>{getLabel(383336, "提交")}</Button>,
                   <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@c428qv@goBack`} onClick={this.back}>{getLabel(83823, "返回")}</Button>
                 ]}>
        <div className="wea-meeting-topic-time">
          <MeetTopicTimeForm ecId={`${this && this.props && this.props.ecId || ''}_MeetTopicTimeForm@k7lb9c`} initFunc={(form) => {this.form = form}}/>
        </div>
      </WeaDialog>
    );
  }

  open = (record) => {
    this.setState({
      visible: true,
      record: record,
      datas: []
    }, () => {
      let {meetingId} = this.props;
      Apis.getTopicDate({meetingid: meetingId, topicid: record.id}).then((result) => {
        this.form.onChange(result.data);
      });
    });
  }

  back = () => {
    this.setState({
      visible: false,
      record: {}
    }, this.form.clear);
  }


  submit = () => {
    let {setTopicNewTime} = this.props.meetingDialog;
    let {meetingId} = this.props;
    const {record} = this.state;
    this.form.validateFieldsAndScroll((values = {}) => {
      let saveObj = {};
      saveObj.meetingid = meetingId;
      saveObj.topicid = record.id;
      Object.entries(values).forEach((entry) => {
        let idx = entry[0];
        if(entry[1].begindate){
          saveObj["begindate_" + idx] = entry[1].begindate;
          saveObj["begintime_" + idx] = entry[1].begintime;
          saveObj["enddate_" + idx] = entry[1].enddate;
          saveObj["endtime_" + idx] = entry[1].endtime;
        }else{
          let beginMoment = moment(entry[1].range[0]);
          let endMoment = moment(entry[1].range[1]);
          saveObj["begindate_" + idx] = beginMoment.format("YYYY-MM-DD");
          saveObj["begintime_" + idx] = beginMoment.format("HH:mm");
          saveObj["enddate_" + idx] = endMoment.format("YYYY-MM-DD");
          saveObj["endtime_" + idx] = endMoment.format("HH:mm");
        }  
      });
      saveObj.rows = Object.entries(values).length;
      Apis.saveTopicDate(saveObj).then((result) => {
        setTopicNewTime(meetingId, record.id, result.data);
        this.back();
      });
    });
  }

}

export default MeetTopicTimeDialog;